import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
import { RegisterDto } from './dto/register.dto';
import { User } from '../user/entities/user.entity';

/**
 * 认证服务
 */
@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  /**
   * 验证用户
   */
  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.userService.findByUsername(username);

    if (!user) {
      return null;
    }

    // 检查用户状态
    if (user.status === 0) {
      throw new UnauthorizedException('账号已被禁用');
    }

    // 验证密码
    const isPasswordValid = await user.validatePassword(password);
    if (!isPasswordValid) {
      return null;
    }

    // 排除密码字段
    const { password: _, ...result } = user;
    return result;
  }

  /**
   * 用户登录
   */
  async login(user: any) {
    const payload = {
      username: user.username,
      sub: user.id,
      role: user.role,
    };

    const userInfo = await this.userService.findById(user.id);

    return {
      accessToken: this.jwtService.sign(payload),
      user: {
        id: userInfo.id,
        username: userInfo.username,
        email: userInfo.email,
        nickname: userInfo.nickname,
        avatar: userInfo.avatar,
        role: userInfo.role,
      },
    };
  }

  /**
   * 用户注册
   */
  async register(registerDto: RegisterDto) {
    const user = await this.userService.create({
      username: registerDto.username,
      email: registerDto.email,
      password: registerDto.password,
      nickname: registerDto.nickname || registerDto.username,
    });

    // 排除密码字段
    const { password: _, ...result } = user;

    return {
      message: '注册成功',
      user: result,
    };
  }

  /**
   * 刷新 Token
   */
  async refreshToken(user: any) {
    const payload = {
      username: user.username,
      sub: user.id,
      role: user.role,
    };

    return {
      accessToken: this.jwtService.sign(payload),
    };
  }
}

